define(function(require, exports, module){
	require("resource/js/easyui/themes/icon.css");
	require("resource/js/easyui/easyloader.js");
	require("resource/font-awesome-4.7.0/css/font-awesome.min.css");
	var ajax = require("resource/js/component/ajax.js");
	var EUtil = require("resource/js/component/easyutil.js");
	var CONST = require('oa/act/js/actcont.js');
	var backDlg = require("resource/js/component/backDialog");
	var dgutil,datagridconfig;
	var currentUser;
	var currentUser = indexApp.exec('user');
	if(currentUser==undefined || currentUser == null){
		indexApp.exec('user',function(obj){
			currentUser = obj;
		});
	}
	var initProgressPage = function(){
		var param = $("#searchform").serializeJson();
		param.moudelType = CONST.ACT_MOUDEL_TYPE.APPROVAL;
		param.phoneStatus = '0';
		ajax.init().success(function(code,msg,data){
			if(data.total!=undefined && data.total>0){
				$('#formviewdatagrid').datagrid('loadData', data.rows);
			}else{
				$('#formviewdatagrid').datagrid('loadData', []);
			}
		}).post(BASEPATH+"/oa/act/approval/progress/queryProgress.htm",param);
	};
	
	/**
	 * 新建流程
	 */
	var addDialogInit = function(baseUrl){
		backDlg.openBackDialog({
			href:BASEPATH+'/view/oa/act/approval/progress/add',
			title:'新建流程',
			backLoadFun: function() {
				initProgressPage();
			}
		});
	};
	/**
	 * 排序
	 */
	var saveOrder = function(baseUrl){
		var data = $("#formviewdatagrid").datagrid("getData");
		var saveArr = [];
		$.each(data.rows,function(i,val){
			var saveInfo;
			if(val.status){
				saveInfo = {business_id:val.business_id,order_num:i,status:val.status};
			}else{
				saveInfo = {business_id:val.business_id,order_num:i,status:1};
			}
			saveArr.push(saveInfo);
		});
		ajax.init().success(function(code,msg,data){
			if(code=='0'){
				$.messager.show({
					title:'系统消息',
					msg:'保存排序成功！',
					timeout:5000,
					showType:'slide'
				 });
				initProgressPage();
			}
		}).contentType("application/json").post(baseUrl,JSON.stringify(saveArr));
	};
	/**
	 * 启用/禁用
	 */
	var updateProcessStatus = function(baseUrl,row){
		if(row.status == 0){
			row.status = 1;
		}else{
			row.status = 0;
		}
		var param = {businessId:row.business_id,status:row.status};
		ajax.init().success(function(code,msg,data){
			initProgressPage();
		}).post(BASEPATH+"/oa/act/approval/progress/updateProgressStatus.htm",param);
	};
	/**
	 * 审核人设置
	 */
	var setProcessPerson = function(baseUrl,row){ 
		backDlg.openBackDialog({
			href:BASEPATH+"/view/oa/act/approval/progress/userset_table",
			title:'审核人设置',
			params:{
				processKey:row.process_key,
				processName:row.process_name,
				nodeNum:row.nodenum,
				branchValId:row.branchvalid,
				is_defined:row.is_defined
			},
			onLoad:function(){
				if(window.sessionStorage){
					window.sessionStorage.ACT_SETUSER_PARAMS=JSON.stringify(this.params); 
				}else{
					alert('您的浏览器版本太低');
				}
			},
			backLoadFun: function() { //返回回调方法
				initProgressPage();
			}
		});
	};
	/**
	 * 抄送人设置
	 */
	var setCopyPerson = function (baseUrl,row){
		require.async("resource/js/component/vitoBooks/vitobooks.js",function(){
			var copyPersonList=[];
			ajax.init().success(function(code,msg,data){//查询该流程默认抄送人
				if(code == 0){
					data.forEach(function(item){
						copyPersonList.push(item.userId);
					})
				}
			}).contentType('application/json').sync().post(BASEPATH+"/oa/actCC/queryProcessCopyPerson.htm",JSON.stringify({processkey:row.process_key}));
			setCopyPerson.dlg = new $("<div id='ccdlg'></div>").appendTo("body").vitoBooks({
				checkType:"checkbox",
				defaultUrl:'user',
				nodeType : 'user',
				closed: false,
				title:"抄送人员选择",
				backfill:true,
				checks:copyPersonList,
				onSave:function(nodes){
				   var copyUserList=[];
				   $.each(nodes,function(i,val){
					   if($.inArray(val.id,copyUserList)==-1){
						   copyUserList.push(val.id);
					   }
				   });
				   var param = {processkey:row.process_key,userIds:copyUserList};
					ajax.init().success(function(code,msg,data){
						if(code == 0){
							$.messager.show({
								title:'系统消息',
								msg:msg,
								timeout:1000,
								showType:'slide'
							 });
						}
					}).contentType('application/json').post(BASEPATH+"/oa/actCC/saveProcessCopyPerson.htm",JSON.stringify(param));
				}
			});
		});
	};
	/**
	 * 节点属性设置
	 */
	var updaeNodeSetting = function(baseUrl,row){
		backDlg.openBackDialog({
			href:BASEPATH+baseUrl+'?key='+row.process_key,
			title:row.business_name+'-节点设置',
		});
	}
	var conf = {
		type:"apkmanage",
		name:"APK",
		columns:[[
					 {field: 'business_id', title: '<input style="height:17px;width:17px;" type="radio" disabled>', width: 30,
						formatter: function(value, row, index) {
						return '<input name="ck" style="height:17px;width:17px;" type="radio">';
					 }},
			         {field:'icon_url',title:'流程图片',width:100,align:'center',height:50,formatter:function(value,row,index){
							if (value){
								return "<img class='click' style='width:30px;height:30px;' src='"+BASEPATH+value+"'/>";
							}
			        	}},
			         {field:'business_name',title:'流程名称',width:100,align:'center',height:50,formatter:function(value,row,index){
							if (value){
								return "<span title='鼠标按住可拖动排序'>"+value+"</span>";
							}
			        	}},
			         {field:'form_name',title:'关联表单',width:100,align:'center',height:50,formatter:function(val,row,i){
			        	 if(val){
			        		 return val;
			        	 }else{
			        		 return '<span style="color:#c3c0c0">系统模板</span>';
			        	 }
			         }},
			         {field:'status',title:'状态',width:100,align:'center',height:50,formatter:function(val,row,i){
			        	 if(val=='0'){
			        		 return "<span style='color:#61b361'>已启用</span>";
			        	 }else{
			        		 return "<span style='color:#ff0000'>已停用</span>";
			        	 }
			         }}
			    ]]
	}
	module.exports={
		init:function(){
			$(".pull .tab").click(function(){
				$(this).addClass("tab-select").siblings().removeClass("tab-select");
			});
			$(".pull-left").click(function(){
				var center = $("body").layout().layout("panel","center");
				center.panel("refresh","formadd");
			});
			var buttons ={ 
					title:{
						_class:"",
						text:"流程管理（上下拖动可进行排序）"
					},
					btn:[
					     {
					    	 iconCls: 'icon-search',
					    	 url:'/oa/act/approval/progress/queryProgress.htm',
					    	 text:"查询",
					    	 addClass:'l-btn-display',
					    	 handler: function(){initProgressPage();}
					     },
					     {
					    	 iconCls: 'icon-add',
					    	 addClass:'l-btn-display',
					    	 text:"添加",
					    	 url:'/view/oa/act/approval/progress/add',
					    	 handler:addDialogInit
					     },
					     {
					    	 iconCls: 'icon-remove',
					    	 addClass:'l-btn-display',
					    	 text:"删除",
					    	 url:'/oa/act/approval/progress/deleteProgress.htm',
					    	 needRow:true,
					    	 handler:function(baseUrl,row){
					    		 $.messager.confirm('系统提示','<label style="color:red;">流程删除后将无法查看历史数据，请谨慎操作！</label></br>您确定要删除吗？',function(r){    
					    			    if (r){    
					    			    	ajax.init().success(function(code,msg,data){
								    			 if(code=="0"){
								    				 $.messager.show({
									    					title:'系统消息',
									    					msg:msg,
									    					timeout:5000,
									    					showType:'slide'
									    				 });
										    			 initProgressPage();
								    			 }
							    			}).post(baseUrl,{processKey:row.process_key});
					    			    }    
					    			});
					    		 
					    	 }
					     },	
					     {
					    	 iconCls: 'icon-icon1_32',
					    	 addClass:'l-btn-display',
					    	 text:'设置',
					    	 url:'/view/oa/act/approval/progress/nodeSetting',
					    	 needRow:true,
					    	 handler:updaeNodeSetting
					     },
					     {
					    	 iconCls: 'icon-icon1_32',
					    	 addClass:'l-btn-display',
					    	 text:"审批人设置",
					    	 //url:'/view/oa/act/approval/progress/userset',
					    	 url:'/view/oa/act/approval/progress/userset_table',
					    	 needRow:true,
					    	 handler:setProcessPerson
					     },
					     {
					    	 iconCls: 'icon-icon1_32',
					    	 addClass:'l-btn-display',
					    	 text:"抄送人设置",
					    	 url:'/view/oa/act/approval/progress/userset_table',
					    	 needRow:true,
					    	 handler:setCopyPerson
					     },
					     {
					    	 iconCls: 'icon-icon1_42',
					    	 addClass:'l-btn-display',
					    	 text:"启用/禁用",
					    	 url:'/oa/act/approval/progress/updateProgressStatus.htm',
					    	 needRow:true,
					    	 handler:updateProcessStatus
					     },
					     {
					    	 iconCls: 'icon-icon1_19',
					    	 addClass:'l-btn-display',
					    	 text:"保存排序",
					    	 url:'/oa/act/approval/progress/updateProgressOrder.htm',
					    	 handler:saveOrder
					     },
					     ]};
			datagridconfig = {
					fitColumns:true,
	                rownumbers:true,
					toolbar:buttons,
					columns:conf.columns,
					eid:"formviewdatagrid",
					check:true,
					pagination:false,
					singleSelect:true,
					args:"searchform",
					fit: true,
					onSelect:function(index, row){
						var btns = $(".datagrid-toolbar").find("a");
						if(row.status == '0'){
							$(btns[6]).find('.l-btn-icon').attr('class','l-btn-icon icon-icon1_80');
							$(btns[6]).find('.l-btn-text').text("禁用");
						}else{
							$(btns[6]).find('.l-btn-icon').attr('class','l-btn-icon icon-icon1_13');
							$(btns[6]).find('.l-btn-text').text("启用");
						}
					},
					onLoadSuccess:function(){
						var btns = $(".datagrid-toolbar").find("a");
						if(!$(btns[6]).hasClass('easyui-tooltip')){
							$(btns[6]).addClass('easyui-tooltip');
							$(btns[6]).tooltip({
								  position: 'top',   
								  content: '<span style="color:#fff">提示：上下拖拽可排序</span>',
								    onShow: function(){
								    	$(this).tooltip('tip').css({   
								    		backgroundColor: '#666',
								    		borderColor: '#666'        
								    			});
								    }
							});	
						}			
						$(this).datagrid('enableDnd');
					},
					onClickRow:function(index,row){
						$(event.target.closest('tr')).find("input[name=ck]").prop("checked",true);
					}
			};
			using(["datagrid","droppable","draggable"],function(){
				setTimeout(function(){
					seajs.use("oa/act/approval/progress/js/datagrid-dnd.js", function(progress) {
						$('#formviewdatagrid').datagrid(datagridconfig);
						EUtil.showBTN(undefined,datagridconfig);
					});
					initProgressPage();
				},100);
			});
		}
	}
});

